
unit player;

{$mode objfpc}{$H+}{$J-}
interface

uses FGL, SDL2, vector2, SysUtils, input_handler,math,cfg, glog, game_object, Classes;

type
  TPlayer = class(TGameObject)
  public
    baseRotation, joypadId, targetApproachSpeed: integer;
    orbitScale: single;
    target: TVector2;
    constructor Create;
    procedure Update();
      override;
  private
    speed: integer;
    procedure HandleInput;
  end;

implementation

procedure TPlayer.HandleInput;

var
  v: TVector2;
  f: integer;
begin
  v.x := 0;
  v.y := 0;
  f := 0;
  if TInputHandle.Instance().IsKeyDown(SDL_SCANCODE_RIGHT) then
    v.x := v.x + 1;
  if TInputHandle.Instance().IsKeyDown(SDL_SCANCODE_LEFT) then
    v.x := v.x - 1;

  if v.x >= 0 then
    f := SDL_FLIP_NONE
  else
    f := SDL_FLIP_HORIZONTAL;

  if v.isZero then
    angle := 0
  else
    angle := round(RadToDeg(arccos(abs(v.x) / v.length)));

  writelnlog('angle:%f', [angle]);
  flip := f;

  if samevalue(v.x, 0) then
    velocity.x := lerp(velocity.x, 0, acceleration.x * 2)
  else
    velocity.x := lerp(velocity.x, v.x * speed, acceleration.x);

  writelnlog('player v:%s,velocity:%s', [v.toString, velocity.toString]);
end;

procedure TPlayer.Update;

var
  ddx, dx, dy: single;
begin
  HandleInput;

(*
  scale := scale + (-1.0 / 60.0) * sin(self.animationCounter / (FPS * 2));
  dx := 2.5 * orbitScale * cos(self.animationCounter / (FPS * 2));
  dy := 1.0 * orbitScale * sin(self.animationCounter / (FPS * 2));
  velocity.x := dx;
  velocity.y := dy;

  self.currentFrame := round(self.animationCounter * 6 / FPS) mod self.animationFrames;

  ddx := acceleration.x;
  if samevalue(ddx, 0.0) then
    ddx := ddx + dx;

  if ddx > 0 then
    flip := SDL_FLIP_NONE
  else if ddx < 0 then
    flip := SDL_FLIP_HORIZONTAL;

  if (flip and SDL_FLIP_HORIZONTAL) = SDL_FLIP_HORIZONTAL then
    angle := 0 - baseRotation
  else
    angle := baseRotation;
    *)
  (*
  velocity.Normalize;
  velocity := velocity * speed;
  *)

  self.currentFrame := round(self.animationCounter * 8 / FPS) mod
    self.animationFrames;
  writelnlog('%d;%d', [self.animationFrames, self.currentFrame]);
  position := position + velocity;
  Inc(animationCounter);
end;

constructor TPlayer.Create;
begin
  inherited Create;
  baseRotation := 0;
  joypadId := 0;
  scale := 1.5;
  orbitScale := 1.0;
  speed := 3;
  currentRow := 0;
  currentFrame := 0;

  acceleration.x := 0.3;
  acceleration.y := 9.8;
end;

end.
